package com.CMUBiS.PageControllers;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import com.CMUBiS.Data.Error;
import com.CMUBiS.Data.GlobalErrors;
import com.CMUBiS.Data.GlobalVars;
import com.CMUBiS.util.Bid;
import com.CMUBiS.util.CheckInputs;
import com.CMUBiS.util.Item;
import com.CMUBiS.util.StopWatch;

/**
 * This controller processes data for the MyAccount servlet
 * 
 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
 * @version 0.1
 * @since 0.1
 * @date 04/05/2011
 */

public class MyAccountController extends PageController{
	private final static String OLD = "&old=1";
	
	// Variables passed in the request
	private int userID = -1;
	private String authToken = null;
	private String welcome = null;
	
	// Structures to hold the DB data
	private String username = null;
	ArrayList<Bid> currentBids = null;
	ArrayList<Bid> oldBids = null;
	ArrayList<Item> currentSellingItems = null;
	ArrayList<Item> oldSellingItems = null;
	
	// Structures to hold the parsed page data
	private String updateDetailsURL = null;
	private String welcomeMessage = "";
	private String[] currentBidsURLs = null;
	private String[] oldBidsURLs = null;
	private String[] currentSellingItemURLs = null;
	private String[] oldSellingItemURLs = null;
	
	/**
	 * This method checks the page for any input errors that may have come from Client generator error
	 * These would need to be check in real life to stop users attempting to hack and mess with things
	 * 
	 * @param request
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void checkInputs(HttpServletRequest request){
		StopWatch timer;
		if(GlobalVars.collectStats){
			timer = new StopWatch();
			timer.start();
		}
		
		if(request != null){
			//super.checkInputs(request);
			
			// Get the userID (if exists), we will pass it along to the next pages
			try{
				this.userID = CheckInputs.checkUserID(request);
			}
			catch(Error e){
				//if(!this.errors.contains(e))
					//this.errors.add(e);
			}
			
			// Get the authToken (if exists), we will pass it along to the next pages
			try{
				this.authToken = CheckInputs.checkAuthToken(request);
			}
			catch(Error e){
				//if(!this.errors.contains(e))
					//this.errors.add(e);
			}
			
			// Get if the welcome message should be passed, if anything is passed for welcome we'll display it
			this.welcome = CheckInputs.getParameter(request, "welcome");
			if(!this.welcome.equals(EMPTY)) this.welcome = "&welcome=1";
		}
		
		// Calculate how long that took
		if(GlobalVars.collectStats){
			timer.stop();
			this.totalGetParamTime += timer.getTimeTaken();
		}
	}

	/**
	 * This method get the data needed for the HTML4 page from the database
	 * 
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void getHTML4Data() {	
		StopWatch timer;
		if(GlobalVars.collectStats){
			timer = new StopWatch();
			timer.start();
		}
		
		/*
		 * The userID and authToken must match to see personal data, we must check before reading anything from
		 * the database
		 */
		if(true || GlobalVars.db.checkAuthToken(userID, authToken)){
			// Get the user's username
			this.username = GlobalVars.db.getFirstName(userID);
			
			// Get the users current bids
			this.currentBids = GlobalVars.db.getCurrentBids(userID);
			
			// Get the user's previous bids
			this.oldBids = GlobalVars.db.getOldBids(userID);
			
			// Get the items that the user is selling
			this.currentSellingItems = GlobalVars.db.getCurrentSellingItems(userID);
			
			// Get the items the user is currently selling
			this.oldSellingItems = GlobalVars.db.getOldSellingItems(userID);
		}
		else{
			//if(!this.errors.contains(GlobalErrors.cannotAuthenticate))
				//this.errors.add(GlobalErrors.cannotAuthenticate);
		}
		
		// Calculate how long that took
		if(GlobalVars.collectStats){
			timer.stop();
			this.totalDBtime += timer.getTimeTaken();
		}
	}

	/**
	 * This method processes all of the data that was read from the database such that it is ready to be printed
	 * on to the page. We try to do as much of the page logic here as possible
	 * 
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void processHTML4() {
		StopWatch timer;
		if(GlobalVars.collectStats){
			timer = new StopWatch();
			timer.start();
		}
		
		/*
		 * Create the links for the items the user is currently bidding on
		 */
		if(this.currentBids != null && this.currentBids.size() > 0){
			int length = this.currentBids.size();
			this.currentBidsURLs = new String[length];
			
			for(int i=0; i<length; i++)
				this.currentBidsURLs[i] = this.makeItemLink(this.currentBids.get(i).getItem(), EMPTY);
		}
		
		/*
		 * Create the links for the old items that the user bid on
		 */
		if(this.oldBids != null && this.oldBids.size() > 0){
			int length = this.oldBids.size();
			this.oldBidsURLs = new String[length];
			
			for(int i=0; i<length; i++)
				this.oldBidsURLs[i] = this.makeItemLink(this.oldBids.get(i).getItem(), OLD);
		}
		
		/*
		 * Create the links for the current items that the user is selling
		 */
		if(this.currentSellingItems != null && this.currentSellingItems.size() > 0){
			int length = this.currentSellingItems.size();
			this.currentSellingItemURLs = new String[length];
			
			for(int i=0; i<length; i++)
				this.currentSellingItemURLs[i] = this.makeItemLink(this.currentSellingItems.get(i), EMPTY);
		}
		
		/*
		 * Create the links for the current old items that the user sold
		 */
		if(this.oldSellingItems != null && this.oldSellingItems.size() > 0){
			int length = this.oldSellingItems.size();
			this.oldSellingItemURLs = new String[length];
			
			for(int i=0; i<length; i++)
				this.oldSellingItemURLs[i] = this.makeItemLink(this.oldSellingItems.get(i), OLD);
		}
		
		// Create the update details URL
		updateDetailsURL = "<a href=\"./updateuserdetails?userID=" + this.userID + "&authToken=" + this.authToken + "\">Update details</a>";
		
		// If the user is new we'll give them the welcome message
		if(!this.welcome.equals(EMPTY))
			this.welcomeMessage = "Welcome " + this.username + "!" + " We hope you buy lots of items!";
		
		// Calculate how long that took
		if(GlobalVars.collectStats){
			timer.stop();
			this.totalProcessingTime += timer.getTimeTaken();
		}
	}
	
	/**
	 * Gets the HTML5 data from the database
	 * 
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void getHTML5Data(){
		StopWatch timer;
		if(GlobalVars.collectStats){
			timer = new StopWatch();
			timer.start();
		}
		
		// Calculate how long that took
		if(GlobalVars.collectStats){
			timer.stop();
			this.totalDBtime += timer.getTimeTaken();
		}
	}
	
	/**
	 * Processes the HTML5 data that is needed to create the page
	 * 
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void processHTML5(){
		StopWatch timer;
		if(GlobalVars.collectStats){
			timer = new StopWatch();
			timer.start();
		}
		
		
		
		// Calculate how long that took
		if(GlobalVars.collectStats){
			timer.stop();
			this.totalProcessingTime += timer.getTimeTaken();
		}
	}
	
	/**
	 * This makes the hyperlink to the items pages. The old parameter tells the DB to look in the current database
	 * or the old database
	 * 
	 * @param item The item to be linked to
	 * @param old If the item is in the old database
	 * @return String of hyperlink to item
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	private String makeItemLink(Item item, String old){
		StringBuffer buf = new StringBuffer();
		
		// If the item is null, i.e. missing we will just say null
		if(item == null){
			buf.append("Sorry, item missing");
		}
		else{
			// The userID and authToken must be present or we would not be displaying the page
			buf.append("<a href=\"viewitem?userID=");
			buf.append(userID);
			buf.append("&authToken=");
			buf.append(authToken);
			buf.append("&itemID=");
			buf.append(item.getID());
			buf.append(old);
			buf.append("\">");
			buf.append(item.getName());
			buf.append("</a>");
		}
		return buf.toString();
	}
	
	/**
	 * Returns the current userID as a String
	 * 
	 * @return String the userID
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public String getUserIDString(){
		return Integer.toString(this.userID);
	}
	
	/**
	 * Returns the authToken sent to the page
	 * 
	 * @return string the authToken
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public String getAuthTokenString(){
		return this.authToken;
	}
	
	/**
	 * Gets the welcome message for the user
	 * 
	 * @return String with message for user
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public String getWelcomeMessage(){
		return this.welcomeMessage;
	}
	
	/**
	 * Returns the URL to the update user details page
	 * 
	 * @return String URL to update user details page
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public String getUpdateUserDetailsURL(){
		return this.updateDetailsURL;
	}
	
	/**
	 * Gets the current bids that the user has made
	 * 
	 * @return ArrayList<Bid> of bids the user has made
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public ArrayList<Bid> getCurrentBids(){
		return this.currentBids;
	}
	
	/**
	 * Returns the 
	 * @return
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public String[] getCurrentBiddingItemURLs(){
		return this.currentBidsURLs;
	}
	
	/**
	 * Returns the bids that the user has previously made
	 * 
	 * @return ArrayList<Bid> that the user has previously made
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public ArrayList<Bid> getOldBids(){
		return this.oldBids;
	}
	
	/**
	 * Returns the URLs to link to the items that the user previous bid on
	 * 
	 * @return String[] of URLs to previously bid on items
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public String[] getOldBiddingItemURLs(){
		return this.oldBidsURLs;
	}
	
	/**
	 * Returns the items that the user is currently selling
	 * 
	 * @return ArrayList<Item> of items that the user is currently selling
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public ArrayList<Item> getCurrentSellingItems(){
		return this.currentSellingItems;
	}
	
	/**
	 * Returns the URLs to the items that the user is selling
	 * 
	 * @return String[] of URLs to the items that the user is currently selling
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public String[] getCurrentSellingItemURLs(){
		return this.currentSellingItemURLs;
	}
	
	/**
	 * Returns the old items that the user sold
	 * 
	 * @return ArrayList<Item> of items that the user previously sold
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public ArrayList<Item> getOldSellingItems(){
		return this.oldSellingItems;
	}
	
	/**
	 * Returns the URLs to link to items that the user previously sold
	 * 
	 * @return String[] of URLs that the user previously sold
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public String[] getOldSellingItemURLs(){
		return this.oldSellingItemURLs;
	}
}
